﻿using dreamwork.auth.api.Model.Data;
using DreamWork.Model.ViewModel;
using IdentityServer4;
using IdentityServer4.Configuration;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Validation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace dreamwork.auth.api.Controllers.Account
{
	[Route("api/[controller]")]
	public class TokenController : Controller
	{
		private readonly UserManager<ApplicationUser> _userManager;

        private readonly IConfiguration _configuration;
		public TokenController(UserManager<ApplicationUser> userManager,
            IConfiguration configuration
            )
		{
			_userManager = userManager;
            _configuration = configuration;

        }
		[HttpGet("[action]")]
		public async Task<IActionResult> GetTestToken([FromServices] ITokenService TS,
			[FromServices] IUserClaimsPrincipalFactory<ApplicationUser> principalFactory,
			[FromServices] IdentityServerOptions options)
		{
			var Request = new TokenCreationRequest();
			var user = await _userManager.FindByNameAsync("jerry");
			var token = await GetToken(user, TS, principalFactory, options);
			token.IdentityToken = token.IdentityToken;
			return Ok(token);
		}

		private async Task<DreamWorkToken> GetToken(ApplicationUser user, ITokenService TS,
		 IUserClaimsPrincipalFactory<ApplicationUser> principalFactory,
		 IdentityServerOptions options)
		{
			if (user == null)
			{
				return new DreamWorkToken { IdentityToken = "User does not exist." };
			}
			var IdentityPricipal = await principalFactory.CreateAsync(user);
			var Request = new TokenCreationRequest();
			var IdentityUser = new IdentityServerUser(user.Id.ToString())
			{
				AdditionalClaims = IdentityPricipal.Claims.ToArray(),
				DisplayName = user.UserName,
				AuthenticationTime = DateTime.UtcNow,
				IdentityProvider = IdentityServerConstants.LocalIdentityProvider
			};
			Request.Subject = IdentityUser.CreatePrincipal();
			Request.IncludeAllIdentityClaims = true;
			Request.ValidatedRequest = new ValidatedRequest
			{
				Subject = Request.Subject,
				Options = options
			};
			Request.ValidatedRequest.SetClient(Config.GetClients(_configuration).First(x => x.ClientId == "dreamwork.admin.client"));
			Request.Resources = new Resources(Config.GetIdentityResources(), Config.GetApiResources());

			var Token = await TS.CreateAccessTokenAsync(Request);
			var identityToken = await TS.CreateIdentityTokenAsync(Request);
			Token.Issuer = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host.Value;
			//claims.ForEach(item => Token.Claims.Add(item));

			var TokenValue = await TS.CreateSecurityTokenAsync(Token);
			return new DreamWorkToken { IdentityToken = "Bearer " + TokenValue };
		}
		public class LoginModel
		{
			public string Username { get; set; }
			public string Password { get; set; }
		}
	}
}
